package org.news.web.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.system.domain.SysOss;
import org.dromara.system.domain.vo.SysOssVo;
import org.dromara.system.mapper.SysOssMapper;
import org.news.web.constant.AuthorInfo;
import org.news.web.constant.CreatorsConstant;
import org.news.web.domain.Users;
import org.news.web.domain.vo.UsersVo;
import org.news.web.mapper.UsersMapper;
import org.springframework.stereotype.Service;
import org.news.web.domain.bo.CreatorsBo;
import org.news.web.domain.vo.CreatorsVo;
import org.news.web.domain.Creators;
import org.news.web.mapper.CreatorsMapper;
import org.news.web.service.ICreatorsService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 作者Service业务层处理
 *
 * @author Gu Ci
 * @date 2024-03-29
 */
@RequiredArgsConstructor
@Service
public class CreatorsServiceImpl implements ICreatorsService {

    private final CreatorsMapper baseMapper;


    private final UsersMapper usersMapper;

    private final SysOssMapper SysOssMapper;

    /**
     * 查询作者
     */
    @Override
    public CreatorsVo queryById(Long creatorId){
        CreatorsVo vo = baseMapper.selectVoById(creatorId);
        setImgName(vo);
        return vo;
    }

    /**
     * 查询作者列表
     */
    @Override
    public TableDataInfo<CreatorsVo> queryPageList(CreatorsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Creators> lqw = buildQueryWrapper(bo);
        Page<CreatorsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

        /**
         * 获取用户名称 并且赋值
         */
        if(ObjectUtil.isNotNull(result.getRecords()) && result.getRecords().size() > 0){
            List<Long> ids = result.getRecords().stream().map(CreatorsVo::getUserId).collect(Collectors.toList());
            List<Users> userinfos = usersMapper.selectList(new QueryWrapper<Users>().in("user_id", ids));
            result.getRecords().forEach((item)->{
                userinfos.stream().forEach((user)->{
                    if(user.getUserId().longValue() == item.getUserId().longValue()){
                        item.setUsername(user.getUsername());
                    }
                });
            });
        }
        /**
         * 通过图片ossid 来获取图片链接
         */
        if(ObjectUtils.isNotEmpty(result) && !result.getRecords().isEmpty()){

            List<CreatorsVo> records = result.getRecords();

            Set<String> coverOssIds = records.stream().map((item -> {
                return item.getCoverPhoto();
            })).collect(Collectors.toSet());

            Set<String> pictureOssIds = records.stream().map((item -> {
                return item.getProfileIcture();
            })).collect(Collectors.toSet());


            Set ossIds = new HashSet();
            ossIds.addAll(coverOssIds);
            ossIds.addAll(pictureOssIds);

            List filterIds = ossIds.stream().toList();

            List<SysOss> pts = SysOssMapper.selectList(new QueryWrapper<SysOss>().in("oss_id", filterIds));

            for(int i=0;i<records.size();i++){
                for(int j=0;j< pts.size();j++){
//                    System.out.println("-------- begin-----------");
//                    System.out.println("转换前的数据："+records.get(i).getProfilePicture());
//                    System.out.println("转换后的数据："+Long.valueOf(records.get(i).getProfilePicture()));
//                    System.out.println("对比的数据："+pts.get(j).getOssId());
//                    System.out.println("-------- end-----------");
                    if(records.get(i).getProfileIcture().equals(String.valueOf(pts.get(j).getOssId()))){
                        records.get(i).setPictureUrl(pts.get(j).getUrl());
                    }
                    if(records.get(i).getCoverPhoto().equals(String.valueOf(pts.get(j).getOssId()))){
                        records.get(i).setCoverUrl(pts.get(j).getUrl());
                    }
                }
            }
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询作者列表
     */
    @Override
    public List<CreatorsVo> queryList(CreatorsBo bo) {
        LambdaQueryWrapper<Creators> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Creators> buildQueryWrapper(CreatorsBo bo) {
        LambdaQueryWrapper<Creators> lqw = Wrappers.lambdaQuery();
//       获取模糊查询的用户
        Set<Long> userIds = null;
        if(StringUtils.isNotBlank(bo.getUsername())){
            List<Users> username = usersMapper.selectList(new QueryWrapper<Users>().like("username", bo.getUsername()));
            if(ObjectUtil.isNotNull(username) && username.size() >0){
                userIds = username.stream().map(Users::getUserId).collect(Collectors.toSet());
            }else{
//                查询不到用户 给一个查不到的id
                userIds = new HashSet<>();
                userIds.add(-1l);
            }
        }
        lqw.in(userIds!= null, Creators::getUserId, userIds);
        if(bo.getTitle() != null){
            lqw.likeLeft(Creators::getTitle,','+bo.getTitle());
            lqw.or();
            lqw.likeRight(Creators::getTitle,bo.getTitle()+',');
            lqw.or();
            lqw.like(Creators::getTitle,','+bo.getTitle()+',');
            lqw.or();
            lqw.eq(Creators::getTitle,bo.getTitle());
        }
        lqw.eq(bo.getStatus() != null, Creators::getStatus, bo.getStatus());
        lqw.eq(bo.getLocation() != null, Creators::getLocation, bo.getLocation());
        return lqw;
    }

    /**
     * 新增作者
     */
    @Override
    public Boolean insertByBo(CreatorsBo bo) {
        Creators add = MapstructUtils.convert(bo, Creators.class);
        DFInsert(add);
        validEntityBeforeSave(add);
//        判断该用户是否已经是作者
        Creators user_id = baseMapper.selectOne(new QueryWrapper<Creators>().eq("user_id", add.getUserId()));
        if(ObjectUtil.isNotNull(user_id)){
            throw new ServiceException("该用户存在作者 无法创建 ！！！");
        }
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setCreatorId(add.getCreatorId());
        }
        return flag;
    }

    /**
     * 默认值插入
     *
     * @param add
     */
    public void DFInsert(Creators add) {
        add.setJoinDate(new Date());
        /**
         * 设置数量默认值
         */
        add.setFollowersCount(0l);
        /**
         * 设置网站前缀
         */
        if(StringUtils.isNotEmpty(add.getWebsite())){
            add.setWebsite(CreatorsConstant.PRE_URL()+add.getWebsite());
        }
        if(StringUtils.isNotEmpty(add.getSocialMedia())){
            add.setSocialMedia(CreatorsConstant.PRE_URL()+add.getSocialMedia());
        }
    }

    /**
     * 修改作者
     */
    @Override
    public Boolean updateByBo(CreatorsBo bo) {
        Creators update = MapstructUtils.convert(bo, Creators.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Creators entity){
        //TODO 做一些数据校验,如唯一约束

    }

    /**
     * 批量删除作者
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 模糊查询
     * @param bo
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<CreatorsVo> getListCreators(AuthorInfo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Creators> lqw = Wrappers.lambdaQuery();
        Set<Long> userIds = null;
        if(StringUtils.isNotBlank(bo.getAuthorName())){
            List<Users> username = usersMapper.selectList(new QueryWrapper<Users>().like("username", bo.getAuthorName()));
            if(ObjectUtil.isNotNull(username) && username.size() >0){
                userIds = username.stream().map(Users::getUserId).collect(Collectors.toSet());
            }else{
//                查询不到用户 给一个查不到的id
                userIds = new HashSet<>();
                userIds.add(-1l);
            }
        }
        lqw.in(userIds!= null, Creators::getUserId, userIds);
        lqw.eq(Creators::getStatus,CreatorsConstant.DFHY);



        Page<CreatorsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

        /**
         * 获取用户名称 并且赋值
         */
        if(ObjectUtil.isNotNull(result.getRecords()) && result.getRecords().size() > 0){
            List<Long> ids = result.getRecords().stream().map(CreatorsVo::getUserId).collect(Collectors.toList());
            List<Users> userinfos = usersMapper.selectList(new QueryWrapper<Users>().in("user_id", ids));
            result.getRecords().forEach((item)->{
                userinfos.stream().forEach((user)->{
                    if(user.getUserId().longValue() == item.getUserId().longValue()){
                        item.setUsername(user.getUsername());
                    }
                });
            });
        }
        /**
         * 通过图片ossid 来获取图片链接
         */
        if(ObjectUtils.isNotEmpty(result) && !result.getRecords().isEmpty()){

            List<CreatorsVo> records = result.getRecords();

            Set<String> coverOssIds = records.stream().map((item -> {
                return item.getCoverPhoto();
            })).collect(Collectors.toSet());

            Set<String> pictureOssIds = records.stream().map((item -> {
                return item.getProfileIcture();
            })).collect(Collectors.toSet());


            Set ossIds = new HashSet();
            ossIds.addAll(coverOssIds);
            ossIds.addAll(pictureOssIds);

            List filterIds = ossIds.stream().toList();

            List<SysOss> pts = SysOssMapper.selectList(new QueryWrapper<SysOss>().in("oss_id", filterIds));

            for(int i=0;i<records.size();i++){
                for(int j=0;j< pts.size();j++){
                    if(records.get(i).getProfileIcture().equals(String.valueOf(pts.get(j).getOssId()))){
                        records.get(i).setPictureUrl(pts.get(j).getUrl());
                    }
                    if(records.get(i).getCoverPhoto().equals(String.valueOf(pts.get(j).getOssId()))){
                        records.get(i).setCoverUrl(pts.get(j).getUrl());
                    }
                }
            }
        }
        return TableDataInfo.build(result);
    }

    @Override
    public CreatorsVo getCreatorById(Integer id) {
        if(id == null || id == 0){
            throw new ServiceException("作者不存在！");
        }
        CreatorsVo vo = baseMapper.selectVoById(id);
//        设置用户id
        Users users = usersMapper.selectById(vo.getUserId());
        vo.setUsername(users.getUsername());
//        设置img
        SysOss sysOss = SysOssMapper.selectById(vo.getProfileIcture());
        vo.setPictureUrl(sysOss.getUrl());
        return vo;
    }


    public void setImgName(List<CreatorsVo> result){
        /**
         * 获取用户名称 并且赋值
         */
        if(ObjectUtil.isNotNull(result) && result.size() > 0){
            List<Long> ids = result.stream().map(CreatorsVo::getUserId).collect(Collectors.toList());
            List<Users> userinfos = usersMapper.selectList(new QueryWrapper<Users>().in("user_id", ids));
            result.forEach((item)->{
                userinfos.stream().forEach((user)->{
                    if(user.getUserId().longValue() == item.getUserId().longValue()){
                        item.setUsername(user.getUsername());
                    }
                });
            });
        }
        /**
         * 通过图片ossid 来获取图片链接
         */
        if(ObjectUtils.isNotEmpty(result) && !result.isEmpty()){

            List<CreatorsVo> records = result;

            Set<String> coverOssIds = records.stream().map((item -> {
                return item.getCoverPhoto();
            })).collect(Collectors.toSet());

            Set<String> pictureOssIds = records.stream().map((item -> {
                return item.getProfileIcture();
            })).collect(Collectors.toSet());


            Set ossIds = new HashSet();
            ossIds.addAll(coverOssIds);
            ossIds.addAll(pictureOssIds);

            List filterIds = ossIds.stream().toList();

            List<SysOss> pts = SysOssMapper.selectList(new QueryWrapper<SysOss>().in("oss_id", filterIds));

            for(int i=0;i<records.size();i++){
                for(int j=0;j< pts.size();j++){
//                    System.out.println("-------- begin-----------");
//                    System.out.println("转换前的数据："+records.get(i).getProfilePicture());
//                    System.out.println("转换后的数据："+Long.valueOf(records.get(i).getProfilePicture()));
//                    System.out.println("对比的数据："+pts.get(j).getOssId());
//                    System.out.println("-------- end-----------");
                    if(records.get(i).getProfileIcture().equals(String.valueOf(pts.get(j).getOssId()))){
                        records.get(i).setPictureUrl(pts.get(j).getUrl());
                    }
                    if(records.get(i).getCoverPhoto().equals(String.valueOf(pts.get(j).getOssId()))){
                        records.get(i).setCoverUrl(pts.get(j).getUrl());
                    }
                }
            }
        }
    }





    public void setImgName(CreatorsVo result){
        /**
         * 获取用户名称 并且赋值
         */
        if(ObjectUtil.isNotNull(result)){

            Users users = usersMapper.selectOne(new QueryWrapper<Users>().eq("user_id", result.getUserId()));
            result.setUsername(users.getUsername());
        }
        /**
         * 通过图片ossid 来获取图片链接
         */
        if(ObjectUtils.isNotEmpty(result)){

            SysOssVo sysOssVo = SysOssMapper.selectVoById(result.getProfileIcture());
            result.setPictureUrl(sysOssVo.getUrl());

            SysOssVo sysOssVo1 = SysOssMapper.selectVoById(result.getCoverPhoto());
            result.setCoverUrl(sysOssVo.getUrl());
        }
    }
}
